from web_api import *
from model import userControl

'''
Reference: http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions 
'''
def login_screen(from_page='/', username='', error_msg='' ):
    template = templateFactory()
    ws = webServer()
    '''
     -->> get_parmas = urllib.quote(cherrypy.request.request_line.split()[1])
    if conditions is not None:
        username = cherrypy.session.get(SESSION_KEY)
        if username:
            cherrypy.request.login = username
            for condition in conditions:
                # A condition is just a callable that returns true orfalse
                if not condition():
                    # Send old page as from_page parameter
                    raise cherrypy.HTTPRedirect("/auth/login?from_page=%s" % get_parmas)

    
    '''
    
    
    '''
    Login then send requestor to page rather than home screen...
    '''
    #get_parmas = urllib.quote(cherrypy.request.request_line.split()[1])

    #Removed direcrt web server integration
    #cherrypy.log(msg='Render Login (%s - %s - %s )' %(from_page, username, error_msg), context='', severity=20, traceback=True)
    
    ws.log('Render Login (%s - %s - %s )' %(from_page, username, error_msg))
    return template.render('login.html', {'from_page': from_page, 'err_msg': error_msg})





def checkLoginAndPassword(login, password): 
    
    #cherrypy.log(msg='--- Verifying Password (%s, %s) ' % (login, password), context='', severity=20, traceback=False)
    userCtrlImp = userControl()
    ws = webServer()
    ws.log('--- Verifying Password (%s, %s)' %(login, password), 'checkLoginAndPassword')
    user = userCtrlImp.checkLogin(login, password)
    '''
    Check user information and determine if it is valid
    '''
    if user==None: 
        '''
        Return error message to calling application...
        '''
        return u'Bad username or password. Please try again'
    else:
        '''
        User information is valid, update session information
        ''' 
        
        ws.setSessionValue('UID', user['ID'])
        ws.setSessionValue('FirstName', user['First'])
        ws.setSessionValue('LastName', user['Last'])
        ws.setSessionValue('FullName', "%s %s" %(user['First'], user['Last'])  )
        ws.setSessionValue('Email', user['Email'])
        ws.setSessionValue('isAdmin', user['Admin'])
        
        '''
        #Note: removed direct cheerypy integration. Replaced by adapter class -> webServer....
        cherrypy.session['UID'] = user['ID']
        cherrypy.session['FirstName'] = user['First']
        cherrypy.session['LastName'] = user['Last']
        cherrypy.session['FullName'] = "%s %s" %(user['First'], user['Last'])  
        cherrypy.session['Email'] = user['Email']
        cherrypy.session['isAdmin'] = user['Admin']
        '''

